﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using WatiN.Core;

using WebAutomation.Browsers;

namespace WebAutomation
{
    public class LinkCommand : CommandBase
    {
        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);  

        public LinkCommand(WebBrowserObject browserObject)
        {
            this.Initialize(browserObject);

        }
        public override bool ExecuteCommand(WebBrowserObject browserObject, string[] parameter, string url, string testRepo, string testResultLocation, string dbConnString, ref System.Data.DataSet dataFromDB, ref TestLineResult testLineResult, ref bool stopTest, WebAutoUtils.ITestDataExceptionRules testDataExceptionRules)
        {
            WebBrowserObject.ElementProperties link = new WebBrowserObject.ElementProperties();
            string command = parameter[0];
            testLineResult.LineCommand = command;
            testLineResult.LineParameter = parameter[1];
            if (this.BrowserObject == null)
            {
                this.BrowserObject = browserObject;
            }
            try
            {

                switch (command.ToLower())
                {
                    case "click":
                        string idOrNameOrClassOrValue = parameter[1].Replace("\r\n", "").Trim();

                        link = GetLink(idOrNameOrClassOrValue);
                        if (!link.Exists)
                        {
                            testLineResult.LineMessage = "Could not find link :" + parameter[1];
                            testLineResult.LinePassed = false;
                        }
                        else
                        {
                            string jsScript = browserObject.GetLinkAttributeValue(link.Element,"href");
                         
                            bool hasOnClick =
                                  !string.IsNullOrEmpty(browserObject.GetLinkAttributeValue(link.Element, "onclick"));

                            if (jsScript.Contains("javascript") && hasOnClick)
                            {
                                
                                LinkClick(link.Element);
                                RunJSScript(jsScript);
                                
                            }
                            else
                            {
                                LinkClick(link.Element);
                            }
                            testLineResult.LinePassed = true;
                        }
                        break;

                    case "clicktext":
                        string text = parameter[1].Replace("\r\n", "").Trim();
                        int index = Convert.ToInt32(parameter[2].Replace("\r\n", "").Trim());
                        link = GetLinkByText(text, index);
                        if (!link.Exists)
                        {
                            testLineResult.LineMessage = "Could not find link with text :" + parameter[1];
                            testLineResult.LinePassed = false;
                        }
                        else
                        {
                            string jsScript = browserObject.GetLinkAttributeValue(link.Element, "href");
                            bool hasOnClick = !string.IsNullOrEmpty(browserObject.GetLinkAttributeValue(link.Element, "onclick"));

                            if (jsScript.Contains("javascript") && hasOnClick)
                            {
                               
                                RunJSScript(jsScript);
                                // link.Click();
                            }
                            else
                            {
                                LinkClick(link.Element);
                            }
                            testLineResult.LinePassed = true;
                        }
                        break;
                }






            }
            catch (Exception ex)
            {
                testLineResult.IsFrameworkError = true;
                testLineResult.LineMessage = "Error." + ex.Message+"."+ex.StackTrace;
                testLineResult.LinePassed = false;
            }
            return testLineResult.LinePassed;
        }


        public virtual void RunJSScript(string javaScriptToRun)
        {
            this.BrowserObject.RunScript(javaScriptToRun);

        }

        public virtual void LinkClick(object link)
        {
            BrowserObject.LinkClick(link);

        }

        public WebBrowserObject.ElementProperties GetLinkByText(string text,int index)
        {
            WebBrowserObject.ElementProperties link = new WebBrowserObject.ElementProperties();
            try
            {

                link = this.BrowserObject.GetLinkByText(text,index);

            }
            catch (UnauthorizedAccessException ex) { }
           

            return link;
        }

        public WebBrowserObject.ElementProperties GetLink(string idOrNameOrClassOrValue)
        {
            WebBrowserObject.ElementProperties link = new WebBrowserObject.ElementProperties();
            try
            {
                link = this.BrowserObject.Link(idOrNameOrClassOrValue);

            }
            catch (UnauthorizedAccessException ex) { }
            if (!link.Exists)
            {
                link = _getLinkFromIFrame(this.BrowserObject, idOrNameOrClassOrValue);
            }

            return link;
        }

        private WebBrowserObject.ElementProperties _getLinkFromIFrame(WebBrowserObject browserObject, string valueOrIdOrName)
        {
            WebBrowserObject.ElementProperties link = new WebBrowserObject.ElementProperties();
            object elementLink = null;
            bool elementExists = false;
            try{
                if (browserObject.Frames().Count > 0)
                {
                    for (int i = 0; i <= browserObject.Frames().Count-1; i++)
                    {
                        browserObject.WaitForCompleteIFrame(i, 5000);
                        foreach (var links in browserObject.FrameLinks(i))
                        {
                            string id = browserObject.GetIFrameLinkAttributeValue(i, links.Key, "id");
                            if (id == valueOrIdOrName)
                            {
                                elementLink = links.Value;
                                elementExists = true;
                                break;
                            }
                            id = browserObject.GetIFrameLinkAttributeValue(i, links.Key, "name");
                            if (id == valueOrIdOrName)
                            {
                                elementLink = links.Value;
                                elementExists = true;
                                break;
                            }
                            id = browserObject.GetIFrameLinkClassName(i, links.Key);
                            if (id == valueOrIdOrName)
                            {
                                elementLink = links.Value;
                                elementExists = true;
                                break;
                            }
                            id = browserObject.GetIFrameLinkAttributeValue(i, links.Key, "value");
                            if (id == valueOrIdOrName)
                            {
                                elementLink = links.Value;
                                elementExists = true;
                                break;
                            }

                        }
                       
                    }

                }
                   
            }
            catch (UnauthorizedAccessException ex)
            {

            }

            link.Element = elementLink;
            link.Exists = elementExists;
            return link;
        }
    }
}
